<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="商品名称">
                <a-input placeholder="请输入商品名称" v-model="queryParam.name" allowClear> </a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="供货商">
                <a-select show-search :filter-option="filterOption" v-model="queryParam.supplier_id" allowClear>
                  <a-select-option :value="item.id" v-for="item in allSupplier" :key="item.id">
                    {{ item.supplier_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="商品分类">
                <div class="select">
                  <a-cascader
                    allowClear
                    :options="catList"
                    @change="onCascaderChange"
                    :fieldNames="{ label: 'name', value: 'id', children: 'children' }"
                    placeholder="请选择商品分类"
                  />
                </div>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="配送方式">
                <a-select v-model="queryParam.send_type" allowClear>
                  <a-select-option key="-1"> 全部 </a-select-option>
                  <a-select-option :key="i" v-for="(item, i) of sendType"> {{ item }} </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="价格区间">
                <div class="numberBox" style="display: flex; align-items: center">
                  <div class="inp" style="flex: 1">
                    <a-input-number
                      :precision="2"
                      style="width: 100%"
                      v-model="queryParam.low_price"
                      :min="0"
                    ></a-input-number>
                  </div>
                  <span style="padding: 0 5px">~</span>
                  <div class="inp" style="flex: 1">
                    <a-input-number
                      v-model="queryParam.high_price"
                      :precision="2"
                      style="width: 100%"
                      :min="queryParam.low_price + 0.01"
                    ></a-input-number>
                  </div>
                </div>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item>
                <a-button type="primary" @click="clearData">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :bordered="false" class="card_style_re" style="margin-top: 20px">
      <a-radio-group v-model="queryParam.sort" :style="{ marginBottom: '20px' }" @change="clearData">
        <a-radio-button value="1"> 最新 </a-radio-button>
        <a-radio-button value="2"> 售价 </a-radio-button>
        <a-radio-button value="3"> 采购数 </a-radio-button>
      </a-radio-group>

      <div class="goodsList">
        <div class="item" v-for="item of list" :key="item.id">
          <div class="box">
            <div class="img">
              <img :src="item.pic_url" alt="" />
              <div class="des">
                <a href="javascript:;" @click="goDetail(item.id)">查看详情</a>
                <a class="on" v-if="can_distribution" href="javascript:;" @click="checkGoods(item)">加入选品</a>
              </div>
            </div>

            <div class="txt">
              <h3>{{ item.name }}</h3>
              <div>
                <div>建议零售价<em>￥</em>{{ item.original_price }}</div>
                <div>预估利润<em>￥</em>{{ (item.sale_price - item.price).toFixed(2) }}</div>
                <div>上架时间 {{ item.up_time }}</div>
                <div>配送方式 {{ sendType[item.send_type] || '-' }}</div>
              </div>
              <div class="price"><em>￥</em>{{ item.price }}</div>

              <div class="number">
                <em>{{ item.sold_num }}</em
                >采购数
              </div>

              <div class="name">{{ item.supplier.supplier_name }}</div>
            </div>
          </div>
        </div>
      </div>

      <div style="text-align: right">
        <el-pagination
          :current-page="queryParam.page"
          background
          layout="prev, pager, next"
          :total="totalCount"
          @current-change="(e) => tablePageChange(e)"
        >
        </el-pagination>
      </div>
      <!-- <a-table
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :pagination="{
          total: this.totalCount,
          showSizeChanger: false,
          onChange: this.tablePageChange
        }"
        :columns="columns"
        :data-source="list"
      >
        <div slot="name" slot-scope="text, record">
          <div class="name">
            <div class="pic">
              <img :src="record.pic_url" alt="" />
            </div>
            <div class="info">
              <span>{{ record.name }}</span>
            </div>
          </div>
        </div>
        <div slot="supplier" slot-scope="text, record">
          <div class="name" v-if="record.supplier">
            <div class="info">
              <span>{{ record.supplier.supplier_name }}</span>
            </div>
          </div>
        </div>
        <span slot="price" slot-scope="text"> ￥{{ text || 0 }} </span>
        <div slot="action" slot-scope="scope">
          <a-button type="link" @click="toBindSku(scope)">导入</a-button>
        </div>
      </a-table> -->
    </a-card>

    <!-- 绑定商品的弹窗 -->
    <a-modal title="商品列表" width="1000px" okText="确认导入" v-model="showBind" @ok="leadGood" :destroyOnClose="true">
      <a-table
        :columns="skuColumns"
        :data-source="currentCloud.attrs"
        bordered
        :rowKey="
          (r, i) => {
            return r.id
          }
        "
        :pagination="false"
      >
        <div slot="attr_list" slot-scope="text, goods">
          {{ text.map((el) => el.attr_name).join('-') }}
        </div>
        <div slot="pic" slot-scope="text">
          <img :src="text" alt="" style="width: 48px; height: 48px; border-radius: 2px" />
        </div>
        <div slot="no" slot-scope="text">
          <a-tooltip>
            <template slot="title">
              {{ text }}
            </template>
            <span>{{ text }}</span>
          </a-tooltip>
        </div>
        <span slot="price" slot-scope="text"> ￥{{ text || 0 }} </span>
      </a-table>
    </a-modal>
    <a-modal v-model="isUpdateGoods" @ok="toBindSku">产品已经存在，是否更新</a-modal>
  </page-header-wrapper>
</template>

<script>
import { supplierList, supplierGoods } from '@/api/purchase/purchase'
import { getCloudGoodsInfo, goodsList, leadGood } from '@/api/purchase/business'
import tabList from '@/views/saas/components/tabList.vue'
import { cyyUploadImg } from '@/components/CyyUi'
// import { getGoodsCatList } from '@/api/purchase/supplier'
import { list as getGoodsCatList } from '@/api/purchase/cat'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '商品名称',
    scopedSlots: {
      customRender: 'name',
    },
    width: 200,
  },
  {
    title: '供货商信息',
    scopedSlots: {
      customRender: 'supplier',
    },
    width: 200,
  },
  {
    title: '售价',
    dataIndex: 'price',
    scopedSlots: {
      customRender: 'price',
    },
    sorter: (a, b) => a.price - b.price,
  },
  {
    title: '库存',
    dataIndex: 'num',
    sorter: (a, b) => a.num - b.num,
  },
  {
    title: '采购次数',
    dataIndex: 'sold_num',
    sorter: (a, b) => a.sold_num - b.sold_num,
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
  },
]

const skuColumns = [
  {
    title: '规格名称',
    dataIndex: 'attr_list',
    scopedSlots: {
      customRender: 'attr_list',
    },
  },
  {
    title: '成本价',
    dataIndex: 'price',
    scopedSlots: {
      customRender: 'price',
    },
    sorter: (a, b) => a.price - b.price,
  },
  {
    title: '售价',
    dataIndex: 'sale_price',
    scopedSlots: {
      customRender: 'sale_price',
    },
    sorter: (a, b) => a.sale_price - b.sale_price,
  },
  {
    title: '库存',
    dataIndex: 'num',
    sorter: (a, b) => a.num - b.num,
  },
  // {
  //   title: '重量(g)',
  //   dataIndex: 'weight',
  //   sorter: (a, b) => a.weight - b.weight
  // },
  {
    title: '规格图片',
    dataIndex: 'pic',
    scopedSlots: {
      customRender: 'pic',
    },
  },
  {
    title: '规格货号',
    dataIndex: 'no',
    width: 100,
    scopedSlots: {
      customRender: 'no',
    },
  },
]
export default {
  components: {
    tabList,
    cyyUploadImg,
  },
  data() {
    return {
      mode: '',

      // {
      //   key: 'purchaseGoodsBand',
      //   name: '绑定商品记录',
      // },
      // 搜索参数
      queryParam: {
        page: 1,
        limit: 10,
        name: '',
        supplier_id: '',
        sort: '1',
        // price_type: '',
        low_price: '',
        high_price: '',
      },
      columns,
      list: [],
      // 新增 编辑供货商的表单
      businessForm: {
        logo: '',
      },
      businessRules: {},
      skuColumns,
      // 是否显示绑定商品的弹窗
      showBind: false,
      // 当前正在操作的云仓商品
      currentCloud: {},
      // 当前操作的云仓规格
      currentCloudSku: {},
      // 当前选中的商品
      currentGood: {
        attr: [],
      },
      // 商户所有的商品列表
      allGoods: [],
      // 商户商品的条数
      goodsCount: 0,
      // 商户商品的搜索参数
      goodsQuery: {
        name: '',
        status: 1,
        product_type: 0,
        pageNo: 1,
        pageSize: 10,
      },
      // 所有供货商列表
      allSupplier: [],

      catList: [],
      can_distribution: 0,
      isUpdateGoods: false,

      sendType: ['快递', '集采', '自主配送', '代理配送'],
    }
  },
  created() {
    this.getList()
    this.supplierList()
    this.getCatList()
  },
  methods: {
    async checkGoods(scope) {
      console.log(scope)
      this.getGoodsInfo(scope.id)
      console.log(scope, this.currentCloud)
      const res = await getCloudGoodsInfo({ goods_id: this.currentCloud.id })
      if (res.code === 0) {
        if (res.data.id) {
          this.isUpdateGoods = true
        } else {
          this.toBindSku(scope)
        }
      }
    },
    getCatList() {
      // catListApi({ is_show: -1 }).then(res => {
      //   this.catList = res.data
      // })

      getGoodsCatList({ is_show: 1 }).then((res) => {
        this.catList = res.data
      })
    },
    async getGoodsInfo(goods_id) {
      let res = await supplierGoods({ id: goods_id })
      if (res.code === 0) {
        let goods_info = res.data.list[0]
        goods_info.attrs = JSON.parse(goods_info.attrs)
        this.currentCloud = goods_info
      } else {
        return null
      }
    },

    onCascaderChange(val) {
      this.queryParam.cat_id = val[val.length - 1]
    },

    goDetail(id) {
      this.$router.push({
        path: `/purchase/goods/edit?id=${id}`,
      })
    },

    // 获取供货商列表
    async supplierList() {
      const res = await supplierList({ page: 1, limit: 50 })
      if (res.code == 0) {
        this.allSupplier = res.data.list
      }
    },

    // 分页请求
    tablePageChange(e) {
      this.queryParam.page = e
      this.getList()
    },

    clearData() {
      this.queryParam.page = 1
      this.getList()
    },

    // 获取数据
    async getList() {
      const hide = this.$message.loading('加载中...', 1000)
      const res = await goodsList(this.queryParam)
      if (res.code == 0) {
        this.list = res.data.list
        this.totalCount = res.data.count
        this.can_distribution = res.data.can_distribution
      }
      hide()
    },
    // 绑定商品
    toBindSku(scope) {
      // this.currentCloud = scope
      // console.log('scope,', scope)
      this.showBind = true
      this.isUpdateGoods = false
    },
    // 绑定和解绑操作
    async leadGood() {
      let goods = JSON.parse(JSON.stringify(this.currentCloud))
      // if (!Array.isArray(goods.pic_list)) {
      //   goods.pic_list = JSON.parse(goods.pic_list)
      // }
      // if (!goods.goods_pic_list) {
      //   goods.goods_pic_list = JSON.parse(JSON.stringify(goods.pic_list))
      //   goods.goods_pic_list.unshift({ pic_url: goods.pic_url })
      // }
      // goods.content = goods.desc
      const res = await leadGood({
        id: goods.id,
      })
      if (res.code == 0) {
        this.$message.success('导入成功~')
        this.showBind = false
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
    },
  },
}
</script>
<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 15px;
  }
}
.tip {
  line-height: normal;
  margin-bottom: 0;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}
.name {
  display: flex;
  align-items: center;
  .pic {
    width: 48px;
    min-width: 48px;
    height: 48px;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 24px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .info {
    flex: auto;
    width: 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    span {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    span:nth-child(2) {
      color: rgba(0, 0, 0, 0.45);
      margin-top: 6px;
    }
  }
}
.goods-info {
  display: flex;
  align-items: flex-start;
  .goods-pic {
    width: 48px;
    height: 48px;
    border-radius: 4px;
  }
  .info-box {
    margin-left: 24px;
    .goods-name {
      display: block;
      width: 160px;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}

.goodsList {
  display: flex;
  flex-wrap: wrap;
  margin-left: -24px;

  .item {
    width: 20%;
  }

  .box {
    margin: 0 0 24px 24px;
    border: 1px solid #f0f2f5;
    border-radius: 4px;

    &:hover {
      .img .des {
        opacity: 1;
      }
    }
  }

  .txt {
    padding: 16px;
    color: rgba(0, 0, 0, 0.45);

    h3 {
      font-size: 14px;
      line-height: 24px;
      height: 48px;
      display: -webkit-box;
      white-space: normal;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      word-break: break-all;
      overflow: hidden;
      color: #000;
    }

    .price {
      padding-bottom: 5px;
      color: #ff4d4f;
      font-size: 16px;

      em {
        font-size: 12px;
        font-style: normal;
      }
    }

    .name,
    .number,
    .price {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .number {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      em {
        font-style: normal;
        color: #1890ff;
      }
    }
  }

  .img {
    position: relative;
    padding-top: 100%;

    img {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .des {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      background: #0084fe;
      transition: 0.3s;
      opacity: 0;

      a {
        overflow: hidden;
        text-align: center;
        // width: 50%;
        flex: 1;
        height: 28px;
        line-height: 28px;
        color: #fff;

        &.on:after {
          content: '';
          position: absolute;
          left: 50%;
          top: 50%;
          margin: -6px 0 0 -0.5px;
          width: 1px;
          height: 12px;
          background: #fff;
        }
      }
    }
  }
}
</style>
